package devcontainer

import (
	actions_model "code.gitea.io/gitea/models/actions"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/webhook"
	gitea_web_context "code.gitea.io/gitea/services/context"
	"github.com/emirpasic/gods/utils"
	"github.com/nektos/act/pkg/jobparser"
	"gopkg.in/yaml.v3"
)

func AddWorkflowTask(ctx *gitea_web_context.Context, cmd []string, runnerLabel string) {

	//构建Workflow对象
	steps := make([]Step, len(cmd))
	for i, run := range cmd {
		//校验合法性、安全性, 暂无

		steps[i] = Step{
			Name: "Step" + utils.ToString(i+1),
			Run:  run,
		}
	}
	wf := Workflow{
		Name: "DevStar Workflow",
		On: On{
			Push: struct {
				Branches []string `yaml:"branches"`
			}{
				Branches: []string{"push"},
			},
		},
		Jobs: Jobs{
			CMD: struct {
				RunsOn string `yaml:"runs-on"`
				Steps  []Step `yaml:"steps"`
			}{
				RunsOn: runnerLabel,
				Steps:  steps,
			},
		},
	}
	// 将Workflow对象编码为YAML格式的字节流
	yamlBytes, err := yaml.Marshal(&wf)
	if err != nil {
		log.Error("Error marshaling workflow to YAML: %v", err)
	}
	branch := ctx.Repo.BranchName
	if branch == "" {
		branch = ctx.Repo.Repository.DefaultBranch
	}
	commit, _ := ctx.Repo.GitRepo.GetBranchCommit(branch)
	run := &actions_model.ActionRun{
		Title:             ctx.Repo.Repository.Name, //strings.SplitN(commit.CommitMessage, "\n", 2)[0],
		RepoID:            ctx.Repo.Repository.ID,   //input.Repo.ID
		OwnerID:           ctx.ContextUser.ID,       //input.Repo.OwnerID
		WorkflowID:        "DevStarInternal.yaml",   //dwf.EntryName
		TriggerUserID:     ctx.Doer.ID,              //input.Doer.ID,
		Ref:               ctx.Repo.RefName,         // ref
		CommitSHA:         commit.ID.String(),       //commit.ID.String()
		IsForkPullRequest: false,                    //isForkPullRequest
		Event:             webhook.HookEventPush,    //input.Event
		EventPayload:      string(""),               //json.Marshal(input.Payload)
		TriggerEvent:      "push",                   //dwf.TriggerEvent.Name,
		Status:            actions_model.StatusWaiting,
	}
	vars := map[string]string{}
	jobs, err := jobparser.Parse(yamlBytes, jobparser.WithVars(vars))
	if err != nil {
		log.Error("jobparser.Parse: %v", err)
	}
	if err := actions_model.InsertRun(ctx, run, jobs); err != nil {
		log.Error("InsertRun: %v", err)
	}
}

// Workflow 定义GitHub Actions的工作流结构
type Workflow struct {
	Name string `yaml:"name"`
	On   On     `yaml:"on"`
	Jobs Jobs   `yaml:"jobs"`
}

// On 定义触发条件
type On struct {
	Push struct {
		Branches []string `yaml:"branches"`
	} `yaml:"push"`
}

// Jobs 定义工作的集合
type Jobs struct {
	CMD struct {
		RunsOn string `yaml:"runs-on"`
		Steps  []Step `yaml:"steps"`
	} `yaml:"CMD"`
}

// Step 定义单个工作步骤
type Step struct {
	Name string `yaml:"name"`
	Run  string `yaml:"run"`
}
